//
//  SourceManager.m
//  iMiniTao
//
//  Created by liu nian on 13-8-14.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "SourceManager.h"
#import "SourceRequest.h"
#import "HotSourceRequest.h"
#import "MeSource.h"
#import "UserSourceEntity.h"
#import "CustomSourceEntity.h"

@interface SourceManager ()<ReqDelegate>{
    SourceRequest   *_reqSource;
    MKEnvObserverCenter    *_obCenter;
}
@property (nonatomic, retain) SourceRequest         *reqSource;
@property (nonatomic, retain) HotSourceRequest      *reqHotSource;
@end

static SourceManager * sharedManager;
@implementation SourceManager

+ (SourceManager *)sharedManager{
    if (!sharedManager) {
        sharedManager = [[SourceManager alloc] init];
    }
    return sharedManager;
}
- (id)init
{
    self = [super init];
    if (self) {
        _obCenter = [[MKEnvObserverCenter alloc] init];
    }
    return self;
}

- (void)addObserver:(id<SourceManagerDelegate>)observer
{
    [_obCenter addEnvObserver:observer];
}

- (void)removeObserver:(id<SourceManagerDelegate>)observer
{
    [_obCenter removeEnvObserver:observer];
}

- (void)requestAllSources{
    [self.reqSource requestAllSourcesWithDelegate:self];
}

- (void)requestHotSources{
    [self.reqHotSource requestHotSourcesWithDelegate:self];
}


#pragma mark  get UserSourceEntity
//普通source 使用
- (UserSourceEntity *)getUserSourceEntityWithSID:(NSInteger)sid themeID:(NSInteger)tid{
    
    UserSourceEntity  *uEntity = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserSourceEntity"
                                              inManagedObjectContext:self.managedObjectContext];
    NSPredicate *predicate;
    predicate = [NSPredicate predicateWithFormat:@"(sid == %d) AND (themeid == %d)", sid,tid];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setIncludesPendingChanges:YES];
    
    NSArray * fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if ([fetchArray count]>0) {
        uEntity = [fetchArray lastObject];
    }
    return uEntity;
}

//自定义source使用
- (UserSourceEntity *)getUserSourceEntityWithName:(NSString *)name{
    
    UserSourceEntity  *uEntity = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserSourceEntity"
                                              inManagedObjectContext:self.managedObjectContext];
    NSPredicate *predicate;
    predicate = [NSPredicate predicateWithFormat:@"(name == %@)", name];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setIncludesPendingChanges:YES];
    
    NSArray * fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if ([fetchArray count]>0) {
        uEntity = [fetchArray lastObject];
    }
    return uEntity;
}

- (UserSourceEntity *)getUserSourceEntityWithMesource:(MeSource *)obj{
    UserSourceEntity *entity = nil;
    if (obj.custom || obj.itemtype != ITEMTYPEKEYWORD) {
        entity = [self getUserSourceEntityWithName:obj.name];
    }else{
        entity = [self getUserSourceEntityWithSID:[obj.sid integerValue]
                                          themeID:[obj.themeid integerValue]];
    }
    return entity;
}


#pragma mark custom source
- (CustomSourceEntity *)getCustomSourceEntityWithName:(NSString *)keyword{
    
    CustomSourceEntity  *uEntity = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CustomSourceEntity"
                                              inManagedObjectContext:self.managedObjectContext];

    NSPredicate *predicate;
    predicate = [NSPredicate predicateWithFormat:@"(keyword == %@)", keyword];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:predicate];
    [fetchRequest setIncludesPendingChanges:YES];
    
    NSArray * fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if ([fetchArray count]>0) {
        uEntity = [fetchArray lastObject];
    }
    return uEntity;
}

- (void)getCustomSource{
    NSArray *fetchArray = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CustomSourceEntity"
                                              inManagedObjectContext:self.managedObjectContext];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creatime"
                                                                   ascending:YES];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    
    fetchRequest.fetchLimit = 100;
    fetchRequest.fetchOffset = 0;
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    [fetchRequest setIncludesPendingChanges:YES];
    
    fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if (fetchArray.count == 0) {
        [_obCenter noticeObervers:@selector(mkManagerCustomSourcesDidFinishedWithSources:)
                       withObject:nil];
        return;
    }
    NSMutableArray *returnArray = [[NSMutableArray alloc] initWithCapacity:fetchArray.count];
    for (CustomSourceEntity *obj in fetchArray) {
        MeSource *meObj = [[MeSource alloc] initWithCustomSourceEntity:obj];
        [returnArray addObject:meObj];
    }
    [_obCenter noticeObervers:@selector(mkManagerCustomSourcesDidFinishedWithSources:)
                   withObject:returnArray];
}

- (BOOL)isExistKeyword:(NSString *)keyword{
    if (keyword == nil || [keyword isEqualToString:@""]) {
        return NO;
    }
    
    CustomSourceEntity *oldEntity = [self getCustomSourceEntityWithName:keyword];
    if (oldEntity) {
        return YES;
    }
    return NO;
}
- (void)addCustomSourceKeyword:(NSString *)keyword icon:(NSString *)icon{
    if (keyword == nil || [keyword isEqualToString:@""]) {
        return;
    }
    
    CustomSourceEntity *oldEntity = [self getCustomSourceEntityWithName:keyword];
    if (oldEntity) {
        [oldEntity setKeyword:keyword];
        [oldEntity setIcon:icon];
        NSError *error = nil;
        if (![self.managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
        return;
    }
    CustomSourceEntity *newEntity= [NSEntityDescription insertNewObjectForEntityForName:@"CustomSourceEntity"
                                                                 inManagedObjectContext:self.managedObjectContext];
    [newEntity setKeyword:keyword];
    [newEntity setCreatime:[NSDate date]];
    [newEntity setIcon:icon];
    
    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    [self getCustomSource];
}
- (void)addCustomSourceKeyword:(NSString *)keyword{
    [self addCustomSourceKeyword:keyword icon:nil];
}

- (void)removeCustomSourceKeyWord:(NSString *)keyword{
    if (keyword == nil || [keyword isEqualToString:@""]) {
        return;
    }
    
    CustomSourceEntity *oldEntity = [self getCustomSourceEntityWithName:keyword];
    if (oldEntity) {
        [self.managedObjectContext deleteObject:oldEntity];
        
        if ([oldEntity isDeleted]) {
            NSError *error = nil;
            if (![self.managedObjectContext save:&error]) {
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                abort();
            }
        }
    }
    [self getCustomSource];
}

- (void)getUserSources{
    NSArray *fetchArray = nil;
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserSourceEntity"
                                              inManagedObjectContext:self.managedObjectContext];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortid"
                                                                   ascending:YES];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:entity];
    
    fetchRequest.fetchLimit = 100;
    fetchRequest.fetchOffset = 0;
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    [fetchRequest setIncludesPendingChanges:YES];
    
    fetchArray = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    
    if (fetchArray.count == 0) {
        if ([[ApplicationManager sharedManager] isFirstLanuch]) {
            [self requestAllSources];
            return;
        }
    }
    [self.meSources removeAllObjects];
    for (UserSourceEntity *obj in fetchArray) {
        MeSource *meObj = [[MeSource alloc] initWithUserSourceEntity:obj];
        BMLog(@"1---:%@",meObj.name);
        [self.meSources addObject:meObj];
    }
    [_obCenter noticeObervers:@selector(mkManagerMeSourcesDidFinishedWithSources:)
                   withObject:_meSources];
}

#pragma mark 用户添加分类，包括自定义的分类
- (void)addSource:(MeSource *)source{
    if (source == nil) {
        return;
    }
    [source setIndex:[self.meSources count]];
    [self.meSources addObject:source];
    [self saveMeSource:source];
    NSInteger  index = [_meSources indexOfObjectIdenticalTo:source];
    [_obCenter noticeObervers:@selector(mkModelManagerSubscribeSourcesAtIndex:)
                   withObject:[NSNumber numberWithInteger:index]];
}

- (void)reorderMeSources{
    if (!_meSources && _meSources.count<= 0) {
        return;
    }
    for (int i = 0; i < [_meSources count]; i++) {
        MeSource *obj = [_meSources objectAtIndex:i];
        [obj setIndex:i];
        [self saveMeSource:obj];
    }
}

#pragma mark MeSource
-(void)saveMeSource:(MeSource *)obj{
    if (obj == nil) {
        return;
    }
    
    UserSourceEntity *oldEntity = [self getUserSourceEntityWithMesource:obj];
    if (oldEntity) {
        [oldEntity setSid:[NSNumber numberWithInteger:[obj.sid integerValue]]];
        [oldEntity setName:obj.name];
        [oldEntity setThemeid:[NSNumber numberWithInteger:[obj.themeid integerValue]]];
        [oldEntity setIsCustom:[NSNumber numberWithBool:obj.custom]];
        [oldEntity setDesc:obj.description];
        [oldEntity setSortid:[NSNumber numberWithInteger:obj.index]];
        [oldEntity setIcon:obj.icon];
        [oldEntity setItemtype:[NSNumber numberWithInteger:obj.itemtype]];
        [oldEntity setKeyword:obj.keyword];
        [oldEntity setUrl:obj.url];
        NSError *error = nil;
        if (![self.managedObjectContext save:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
        return;
    }
    UserSourceEntity *newEntity= [NSEntityDescription insertNewObjectForEntityForName:@"UserSourceEntity"
                                                            inManagedObjectContext:self.managedObjectContext];
    [newEntity setSid:[NSNumber numberWithInteger:[obj.sid integerValue]]];
    [newEntity setName:obj.name];
    [newEntity setThemeid:[NSNumber numberWithInteger:[obj.themeid integerValue]]];
    [newEntity setIsCustom:[NSNumber numberWithBool:obj.custom]];
    [newEntity setDesc:obj.description];
    [newEntity setSortid:[NSNumber numberWithInteger:obj.index]];
    [newEntity setIcon:obj.icon];
    [newEntity setItemtype:[NSNumber numberWithInteger:obj.itemtype]];
    [newEntity setKeyword:obj.keyword];
    [newEntity setUrl:obj.url];
    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

- (BOOL)removeMeSource:(MeSource *)obj{
    if (obj == nil) {
        return NO;;
    }
    
    UserSourceEntity *oldEntity = [self getUserSourceEntityWithMesource:obj];
    if (oldEntity) {
        [self.managedObjectContext deleteObject:oldEntity];
        for (MeSource *meSource in self.meSources) {
            if (meSource.itemtype == ITEMTYPECUZYITEM) {
                if ([meSource.themeid isEqualToString:obj.themeid]) {
                    [self.meSources removeObject:meSource];
                    break;
                }
            }else{
                if ([meSource.name isEqualToString:obj.name]) {
                    [self.meSources removeObject:meSource];
                    break;
                }
            }
        }
        
        if ([oldEntity isDeleted]){
            NSError *savingError = nil;
            if ([self.managedObjectContext save:&savingError]){
                //保存，flush到数据库。
                [self reorderMeSources];
                return YES;
            }
            
        }
        
    }
    return NO;
}

- (BOOL)removeTheMeSource:(MeSource *)obj{
    if (obj == nil) {
        return NO;;
    }
    
    UserSourceEntity *oldEntity = [self getUserSourceEntityWithMesource:obj];
    if (oldEntity) {
        BMLog(@"");
        [self.managedObjectContext deleteObject:oldEntity];
        NSInteger index= 0;
        for (MeSource *meSource in self.meSources) {
            if (obj.itemtype == ITEMTYPECUZYITEM) {
                if ([meSource.themeid isEqualToString:obj.themeid]) {
                    index = [self.meSources indexOfObjectIdenticalTo:meSource];
                    [self.meSources removeObject:meSource];
                    break;
                }
            }else{
                if ([meSource.name isEqualToString:obj.name]) {
                    index = [self.meSources indexOfObjectIdenticalTo:meSource];
                    [self.meSources removeObject:meSource];
                    break;
                }
                
            }
            
        }
        if ([oldEntity isDeleted]){
            NSError *savingError = nil;
            if ([self.managedObjectContext save:&savingError]){
                //保存，flush到数据库。
                [self reorderMeSources];
                [_obCenter noticeObervers:@selector(mkModelManagerUnsubscribeSourcesAtIndex:)
                               withObject:[NSNumber numberWithInteger:index]];
                return YES;
            }
            
        }
        
    }
    return NO;
}




#pragma mark ReqDelegate
- (void)finishErrorReq:(id)Req errorCode:(int) errorCode message:(NSString *)message{
    if (Req == self.reqSource) {
        [_obCenter noticeObervers:@selector(mkManagerAllSourcesRequestDidFailed)];
    }
}
- (void)finishSourceReq:(id)Req sources:(NSArray *)sources{
    if ([sources count]>0) {
        //保存频道分类信息
        if ([[ApplicationManager sharedManager] isFirstLanuch]){
            NSInteger index = 0;
            for (int i = 0; i <[sources count] ;i++ ){
                Source *object = [sources objectAtIndex:i];
                if ([object.type intValue] == 2) {
                    
                    MeSource *meSource = [[MeSource alloc] initWithSource:object];
                    meSource.index = index;
                    [self saveMeSource:meSource];
                    index ++;
                }
            }
            //标记已经不是第一次启动
            [[ApplicationManager sharedManager] flagLanuch];
            [self performSelector:@selector(getUserSources) withObject:nil afterDelay:1.0];
        }
        
        [_obCenter noticeObervers:@selector(mkManagerAllSourcesRequestDidFinishedWithSources:)
                       withObject:sources];
    }else{
        [_obCenter noticeObervers:@selector(mkManagerAllSourcesRequestDidFailed)];
    }
}
//HotSource
- (void)finishSourceReq:(id)Req hotSources:(NSArray *)hotSources{
    if (hotSources.count > 0) {
        [_obCenter noticeObervers:@selector(mkManagerHotSourcesDidFinishedWithSources:)
                       withObject:hotSources];
    }
}

#pragma mark getter
- (SourceRequest *)reqSource{
    if (!_reqSource) {
        _reqSource = [[SourceRequest alloc] init];
    }
    return _reqSource;
}
- (HotSourceRequest *)reqHotSource{
    if (!_reqHotSource) {
        _reqHotSource = [[HotSourceRequest alloc] init];
    }
    return _reqHotSource;
}
- (NSMutableArray *)meSources{
    if (!_meSources) {
        _meSources = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _meSources;
}
@end
